<template>
    <view  v-if="curValue && readOnly">
        <svg v-if="curValue"  :id="'barcode_'+id"/>
    </view>
    <view v-else-if="readOnly && !curValue">
        <RxEmpty></RxEmpty>
    </view>
    <view v-else>
        <input  class="ant-input" v-model="curValue" :disabled="readOnly" @input="onChange"/>
    </view>
</template>

<script>
/**
 * 条码
 * https://github.com/lindell/JsBarcode
 */
import MForm from "../js/MForm";
import Util from "@/js/Util.js";
import JsBarcode from 'jsbarcode'
import RxEmpty from "@/components/RxEmpty"
export default {
    name: "MBarCode",
    mixins: [MForm],
    components:{RxEmpty},
    data() {
        return {
            curValue:"",
            id:Util.randomId()
        }
    },
    created() {
        this.initValue(this.value);
    },
    methods: {
        initValue(value) {
            this.curValue = value || "";
            this.genBarCode();
        },
        onChange(e){
            this.setData(e.detail.value);
        },
        //生成条形码
        genBarCode(){
            if(!this.readOnly || !this.curValue){
                return;
            }
            let id='#barcode_'+this.id;
            let text=this.curValue;
            let option={
                //条形码的格式CODE128
                format:"CODE128",
                //线宽
                width:this.metadata.options.lineWidth || 1,
                //条码高度
                height:this.metadata.options.height || 100,
                //线条颜色
                lineColor:"#000",
                //是否显示文字
                displayValue:this.metadata.options.displayValue || false,
                //设置条形码周围的空白区域
                margin:2,
                //设置文本的大小
                fontSize:this.metadata.options.fontSize || 15,
            }
            this.$nextTick(() => {
                JsBarcode(id,text,option);
            });
        },
    },
    watch: {
        value(val) {
            this.initValue(val);
        }
    },
}
</script>

<style scoped>

</style>
